<template>
  <c-button type="primary" :disabled="disabled" @click="start">
    {{ copy }}
  </c-button>
</template>

<script>
export default {
  props: {
    // 文案
    text: {
      type: String,
      default: "获取验证码"
    },
    // 倒计时秒数
    second: {
      type: Number,
      default: 120
    },
    // 开始之前执行事件
    beforeStartFn: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      copy: null,
      time: null,
      timer: null,
      disabled: false
    };
  },
  methods: {
    start() {
      if (this.beforeStartFn) {
        this.beforeStartFn()
          .then(() => {
            this.started();
          })
          .catch(() => {});
      } else {
        this.started();
      }
    },
    started() {
      this.disabled = true;
      this.countdown();
    },
    // 发送短信倒计时
    countdown() {
      let sec = this.time;
      this.timer = setInterval(() => {
        if (sec <= 0) {
          this.copy = "获取验证码";
          this.disabled = false;
          clearInterval(this.timer);
          this.$emit("finish");
        } else {
          this.copy = `重发(${sec--}s)`;
        }
      }, 1000);
    },
    // 重置
    reset() {
      this.copy = "获取验证码";
      this.disabled = false;
      clearInterval(this.timer);
    }
  },
  mounted() {
    this.copy = this.text;
    this.time = this.second;
  }
};
</script>
